import { useState, useEffect } from 'react';
import { Form, Select, Upload, Button, Tooltip, message, Modal } from 'antd';
import { isEmpty, } from 'lodash';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { handleExportExcel } from '@/utils/utils.jsx';
import Api from '../../service';
import styles from './index.module.less';

export default ({ handleOk, handleCancel }) => {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [file1, setFile1] = useState({}); //上传的文件值
  const [file2, setFile2] = useState({});

  const [ecStoreId, setStoreId] = useState('');

  //店铺下拉列表
  const [shopList, setShopList] = useState([]);

  useEffect(() => {
    setVisible(true);
  }, []);

  useEffect(() => {
    if (visible) {
      queryShopList();
    }
  }, [visible]);

  useEffect(() => {
    if (shopList.length) {
      form.setFieldsValue({ ecStoreId: shopList[0].id })
    }
  }, [shopList]);

  //获取店铺列表
  const queryShopList = async () => {
    setLoading(true);
    const { data, success } = await Api.getStoreListOp({
      channelType: 19,
    });
    if (success) {
      const arr = (data || []).filter(item => item.jdExpressCode);//过滤事业编码为空的数据
      setShopList(arr);
      if (arr.length) {
        setStoreId(arr[0].id);
      }
    }
    setLoading(false);
  };

  const exportExcel = (value) => {
    // setLoading(true);
    if (value == 'yundanchaxunliebiao') {
      return window.open('https://qiniu.zhaojiafang.com/销售订单列表模版.xlsx');
      handleExportExcel(`/new-oms-ec/jdCloudOrder/download?type=${2}`, '运单查询数据列表模版.xlsx', () => {
        setLoading(false);
      })
    } else {
      return window.open('https://qiniu.zhaojiafang.com/运单查询数据列表模版.xlsx');
      handleExportExcel(`/new-oms-ec/jdCloudOrder/download?type=${1}`, '销售订单列表模版.xlsx', () => {
        setLoading(false);
      })
    }
  }

  const onOk = () => {
    form.validateFields().then(async () => {
      if (isEmpty(file1)) {
        return Modal.info({ content: '请上传销售订单列表' });
      }
      if (isEmpty(file2)) {
        return Modal.info({ content: '请上传运单查询数据' });
      }
      setLoading(true);
      const { success } = await Api.exportJingdongOrders({
        ecStoreId,
        saleFile: file1,
        logisticsFile: file2,
      });
      setLoading(false);
      if (success) {
        message.info('正在上传中，上传结果请稍后刷新查看订单列表');
        handleOk();
        setVisible(false);
      }
    }).catch(() => {
      // message.info('请先选择店铺')
    })
  }

  const props1 = {
    maxCount: 1,
    onRemove: file => {
      setFile1({})
    },
    beforeUpload: file => {
      setFile1(file)
      return false;
    },
    file1,
  };

  const props2 = {
    maxCount: 1,
    onRemove: file => {
      setFile2({})
    },
    beforeUpload: file => {
      setFile2(file)
      return false;
    },
    file2,
  };

  const handleOpenFile = () => {
    form.validateFields();
    message.info('请先选择店铺');
  }

  const importModal = (val) => {
    return (
      <div className={styles.upLoadBox}>
        <div>
          {
            val == 'xiaoshouliebiao' ? (ecStoreId ? <Upload {...props1}>
              <Button>文件上传</Button>
            </Upload> : <Button onClick={handleOpenFile}>文件上传</Button>)
              :
              (ecStoreId ? <Upload {...props2}>
                <Button>文件上传</Button>
              </Upload> : <Button onClick={handleOpenFile}>文件上传</Button>)
          }
        </div>
        <div className={styles.downButton}>
          {
            val == 'xiaoshouliebiao' ?
              <Button onClick={() => { exportExcel('xiaoshouliebiao') }}>下载模板</Button> :
              <Button onClick={() => { exportExcel('yundanchaxunliebiao') }}>下载模板</Button>
          }
        </div>
      </div>
    )
  }

  // 店铺下拉选项
  const optionStore = !isEmpty(shopList) &&
    shopList.map((d) => (
      <Option key={d.id} value={d.id} label={d.storeName}>
        <Tooltip title={d.storeName}>{d.storeName}</Tooltip>
      </Option>
    ));
  
  return (
    <CommonModal
      visible={visible}
      title='导入云仓运单号'
      onOk={onOk}
      onCancel={()=>setVisible(false)}
      afterClose={handleCancel}
      width={600}
    >

      <div>

        <div style={{ backgroundColor: '#EBF4FF', padding: 10, marginBottom: 10 }}>
          <div>注：1、两个步骤上传的表格，顺序不要错误，可下载模板对比一下</div>
          <div>2、导入2个表格确认上传后，系统会根据两个表格的配比后，在仓库订单里找到它们然后把运单号填充进去，只有待包装之前的订单会导入成功</div>
          <div>3、每个表格最多支持1万条数据</div>
        </div>

        <Form form={form}>
          <Form.Item label="请先选择云仓店铺:" name="ecStoreId" rules={[{ required: true, message: '请选择云仓店铺' }]}>
            <Select
              allowClear
              showSearch
              placeholder="全部"
              optionFilterProp="label"
              style={{ width: '207px' }}
              onChange={e => setStoreId(e)}
              value={ecStoreId}
            >
              {optionStore}
            </Select>
          </Form.Item>
        </Form>
        <div>
          <div><span style={{ color: 'red' }}>*</span> 1.上传销售订单列表</div>
          <div style={{ marginBottom: 10 }}>{importModal('xiaoshouliebiao')}</div>
        </div>
        <div>
          <div><span style={{ color: 'red' }}>*</span> 2.上传运单查询数据列表</div>
          <div style={{ marginBottom: 10 }}>{importModal('yundanchaxunliebiao')}</div>
        </div>
      </div>
      <CommonLoading loading={loading} />
    </CommonModal>
  )
}
